package cn.com.dhcc.turbo.service.registry;

import java.util.Date;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.exch.GapInfo;
import cn.com.dhcc.turbo.service.exch.cmdata.GapInfoService;
import cn.com.dhcc.turbo.service.queue.tlq.TlqOptService;
import cn.com.dhcc.turbo.service.transport.FtpService;

/**
 * 节点初始化
 * @author qiao
 * @2014-6-13 @下午3:14:25
 */
@Service
public class NodeInitService {

	@Autowired
	FtpService ftpService;
	@Autowired
	NodeInfoService nodeInfoService;
	@Autowired
	TlqOptService tlqOptService;
	@Autowired
	private GapInfoService gapInfoService;
	@Autowired
	LocalConfCallBack localConfCallBack;
	@SuppressWarnings("deprecation")
	Logger logger = Log.getDetachLogger(LOGTYPE.FTP);
	@SuppressWarnings("deprecation")
	Logger syslogger = Log.getDetachLogger(LOGTYPE.SYS);

	public void initNode(ServletContext servletContext) {
		try {
			//1,只初始化中央节点(根节点)。其他节点需要按管理关系注册
			initNodeInfo();
			initGap(servletContext);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		servletContext.log("节点初始化成功...");
	}
	/**
	 * 初始化网闸
	 * @throws ServiceException 
	 */
	private void initGap(ServletContext servletContext) throws ServiceException {
		if(NodeInfoParam.hasGap()){
			GapInfo gapInfo = gapInfoService.getGapInfo();
			if(gapInfo==null){
				gapInfo = new GapInfo();
				gapInfo.setId(UUIDGenerator.getUUID());
				gapInfo.setmTime(new Date());
			}
			gapInfo.setFtpIp(NodeInfoParam.GAP_PARAM.IP);
			gapInfo.setFtpPort(NodeInfoParam.GAP_PARAM.Port+"");
			gapInfo.setFtpUser(NodeInfoParam.GAP_PARAM.UserName);
			gapInfo.setFtpPwd(NodeInfoParam.GAP_PARAM.Password);
			gapInfo.setFtpHome(NodeInfoParam.GAP_PARAM.Home);
			
			gapInfoService.insertOrUpdate(gapInfo);
			servletContext.log("网闸信息加载成功!");
		}
		
	}
	private void initNodeInfo() {
		try {
			nodeInfoService.initNodeInfo();
		} catch (NiceException e) {
			throw new RuntimeException(e);
		} catch (ServiceException e) {
			throw new RuntimeException("节点初始化失败", e);
		}
	}

}
